package d4_tcp2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 2024/7/7 完成TCP通信快速入门-服务端开发：要求实现与多个客户端同时通信
 */
public class Server {
    public static void main(String[] args) throws IOException {
        System.out.println("---服务端启动成功----");

        //1.创建ServerSocket的对象,同时为服务端注册端口
        ServerSocket socket = new ServerSocket(8080);

        //2.创建出一个线程池，处理通信管道的任务
       ThreadPoolExecutor pool= new ThreadPoolExecutor(16*2,16*2,0, TimeUnit.SECONDS,
               new ArrayBlockingQueue<>(8), Executors.defaultThreadFactory(),
               new ThreadPoolExecutor.AbortPolicy());


        while (true){
            //2.使用ServerSocket对象,调用一个accept方法 等待客户端接收
            Socket accept = socket.accept();
            System.out.println("有人上线了："
                                +accept.getRemoteSocketAddress());

        //3.把这个客户端对应的socket通信管道,交给一个独立的线程负责
            pool.execute(new ServerReaderRunnable(socket.accept()));

        }
    }
}
